<template>
  <el-select
    v-model="localValue"
    filterable
    remote
    reserve-keyword
    placeholder="仓库"
    :remote-method="searchRepo"
    :loading="loading"
    clearable
    value-key="key"
    class="w-150px"
  >
    <el-option
      v-for="item in options"
      :key="item.value.key"
      :label="item.label"
      :value="item.value"
    ></el-option>
  </el-select>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import { repositoryService } from '@/services/business/repository.service';
import type { Repository, RepoOption } from '@/types/business/repository';

const props = defineProps({
  modelValue: {
    required: true,
    type: null as unknown as undefined,
  },
});

const emit = defineEmits(['update:modelValue']);

const localValue = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value),
});

const options = ref<RepoOption[]>([]);
const loading = ref(false);

const searchRepo = async (query: string) => {
  if (query) {
    loading.value = true;
    try {
      const response = await repositoryService.searchRepositories(query);
      options.value = response.records.map((r: Repository) => ({
        value: {
          id: r.id,
          gitInstance: r.gitInstance,
          repositoryId: r.gitId,
          key: `${r.gitInstance}-${r.gitId}`,
        },
        label: `${r.gitInstance} - ${r.name}`,
      }));
    } catch (error) {
      console.error('Error searching repositories:', error);
      options.value = [];
    } finally {
      loading.value = false;
    }
  } else {
    options.value = [];
  }
};
</script>
